import React, {useEffect, useState} from 'react';
import {
    Alert,
    Badge,
    Button,
    Card,
    Checkbox,
    Col,
    Divider,
    Form,
    Input,
    message,
    Modal,
    Popconfirm,
    Row,
    Select,
    Space,
    Spin,
    Table,
    Tag,
    Tooltip,
    Typography
} from 'antd';
import {
    DeleteOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    LockOutlined,
    MailOutlined,
    ReloadOutlined,
    UserAddOutlined,
    UserOutlined,
    UserSwitchOutlined
} from '@ant-design/icons';
import {createUser, deleteUser, getUsers, updateUser} from '../services/api';
import type {UserData, UsersListResponse} from '../types';

const {Title} = Typography;
const {Option} = Select;
const {confirm} = Modal;
const {Search} = Input;


const Users: React.FC = () => {
    const [loading, setLoading] = useState<boolean>(true);
    const [usersData, setUsersData] = useState<UsersListResponse | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [modalVisible, setModalVisible] = useState<boolean>(false);
    const [modalTitle, setModalTitle] = useState<string>('添加用户');
    const [editingUser, setEditingUser] = useState<UserData | null>(null);
    const [form] = Form.useForm();
    const [searchText, setSearchText] = useState<string>('');
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [filterRole, setFilterRole] = useState<string | null>(null);
    const [filterStatus, setFilterStatus] = useState<string | null>(null);

    // 获取用户列表
    const fetchUsers = async (page: number = 1, pageSize: number = 10) => {
        try {
            setLoading(true);
            const response = await getUsers({
                page,
                pageSize,
                searchText,
                role: filterRole || undefined,
                status: filterStatus || undefined
            });
            const data = response.data;

            if (response.success && data) {
                setUsersData(data);
                setError(null);
            } else {
                setError(response.message || '获取用户列表失败');
            }
        } catch (err: any) {
            setError(err.message || '获取用户列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 初始加载
    useEffect(() => {
        fetchUsers();
    }, [filterRole, filterStatus]);

    // 处理分页变化
    const handlePageChange = (page: number, pageSize?: number) => {
        fetchUsers(page, pageSize);
    };

    // 打开添加用户模态框
    const showAddUserModal = () => {
        setModalTitle('添加用户');
        setEditingUser(null);
        form.resetFields();
        form.setFieldsValue({
            status: 'active',
            role: 'user',
            permissions: ['view_dashboard', 'view_reports']
        });
        setModalVisible(true);
    };

    // 打开编辑用户模态框
    const showEditUserModal = (user: UserData) => {
        setModalTitle('编辑用户');
        setEditingUser(user);
        form.setFieldsValue({
            username: user.username,
            displayName: user.displayName,
            email: user.email,
            role: user.role,
            status: user.status || 'active',
            permissions: user.permissions || ['view_dashboard', 'view_reports'],
            password: '', // 编辑时不填充密码
        });
        setModalVisible(true);
    };

    // 处理模态框确认
    const handleModalOk = () => {
        form.validateFields().then(async (values) => {
            try {
                if (editingUser) {
                    // 更新用户
                    const response = await updateUser(editingUser.username, values);

                    if (response.success) {
                        message.success('用户更新成功');
                        setModalVisible(false);
                        fetchUsers(usersData?.currentPage || 1, usersData?.pageSize || 10);
                    } else {
                        message.error(response.message || '用户更新失败');
                    }
                } else {
                    // 创建用户
                    const response = await createUser(values);

                    if (response.success) {
                        message.success('用户创建成功');
                        setModalVisible(false);
                        fetchUsers(usersData?.currentPage || 1, usersData?.pageSize || 10);
                    } else {
                        message.error(response.message || '用户创建失败');
                    }
                }
            } catch (err: any) {
                message.error(err.message || '操作失败');
            }
        });
    };

    // 处理删除用户
    const handleDeleteUser = (username: string) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined/>,
            content: `确定要删除用户 "${username}" 吗？此操作不可撤销。`,
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const response = await deleteUser(username);

                    if (response.success) {
                        message.success('用户删除成功');
                        fetchUsers(usersData?.currentPage || 1, usersData?.pageSize || 10);
                    } else {
                        message.error(response.message || '用户删除失败');
                    }
                } catch (err: any) {
                    message.error(err.message || '删除失败');
                }
            }
        });
    };

    // 批量删除用户
    const handleBulkDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请至少选择一个用户');
            return;
        }

        confirm({
            title: '批量删除用户',
            icon: <ExclamationCircleOutlined/>,
            content: `确定要删除选中的 ${selectedRowKeys.length} 个用户吗？此操作不可撤销。`,
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                try {
                    // 这里需要后端实现批量删除API
                    message.success(`已删除 ${selectedRowKeys.length} 个用户`);
                    setSelectedRowKeys([]);
                    fetchUsers(usersData?.currentPage || 1, usersData?.pageSize || 10);
                } catch (err: any) {
                    message.error(err.message || '批量删除失败');
                }
            }
        });
    };

    // 批量更新用户状态
    const handleBulkUpdateStatus = (status: 'active' | 'inactive' | 'locked') => {
        if (selectedRowKeys.length === 0) {
            message.warning('请至少选择一个用户');
            return;
        }

        confirm({
            title: `批量${status === 'active' ? '激活' : status === 'inactive' ? '禁用' : '锁定'}用户`,
            icon: <ExclamationCircleOutlined/>,
            content: `确定要${status === 'active' ? '激活' : status === 'inactive' ? '禁用' : '锁定'}选中的 ${selectedRowKeys.length} 个用户吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
                try {
                    // 这里需要后端实现批量更新状态API
                    message.success(`已${status === 'active' ? '激活' : status === 'inactive' ? '禁用' : '锁定'} ${selectedRowKeys.length} 个用户`);
                    setSelectedRowKeys([]);
                    fetchUsers(usersData?.currentPage || 1, usersData?.pageSize || 10);
                } catch (err: any) {
                    message.error(err.message || '批量操作失败');
                }
            }
        });
    };

    // 获取角色标签颜色
    const getRoleTagColor = (role: string) => {
        switch (role.toLowerCase()) {
            case 'admin':
                return 'red';
            case 'user':
                return 'blue';
            case 'guest':
                return 'green';
            default:
                return 'default';
        }
    };

    // 获取状态标签
    const getStatusBadge = (status: string) => {
        switch (status) {
            case 'active':
                return <Badge status="success" text="活跃"/>;
            case 'inactive':
                return <Badge status="default" text="未激活"/>;
            case 'locked':
                return <Badge status="error" text="已锁定"/>;
            default:
                return <Badge status="processing" text={status}/>;
        }
    };

    // 表格行选择配置
    const rowSelection = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys: React.Key[]) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
    };

    // 表格列配置
    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            sorter: true,
        },
        {
            title: '显示名',
            dataIndex: 'displayName',
            key: 'displayName',
            render: (text: string) => text || '-',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            render: (text: string) => text || '-',
        },
        {
            title: '角色',
            dataIndex: 'role',
            key: 'role',
            render: (role: string) => (
                <Tag color={getRoleTagColor(role)}>{role.toUpperCase()}</Tag>
            ),
            filters: [
                {text: '管理员', value: 'admin'},
                {text: '用户', value: 'user'},
                {text: '访客', value: 'guest'},
            ],
            filteredValue: filterRole ? [filterRole] : null,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: string) => getStatusBadge(status),
            filters: [
                {text: '活跃', value: 'active'},
                {text: '未激活', value: 'inactive'},
                {text: '已锁定', value: 'locked'},
            ],
            filteredValue: filterStatus ? [filterStatus] : null,
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            render: (text: string) => text || '-',
            sorter: true,
        },
        {
            title: '最后登录',
            dataIndex: 'lastLogin',
            key: 'lastLogin',
            render: (text: string) => text || '-',
            sorter: true,
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: UserData) => (
                <Space>
                    <Tooltip title="编辑用户">
                        <Button
                            type="text"
                            icon={<EditOutlined/>}
                            onClick={() => showEditUserModal(record)}
                        />
                    </Tooltip>

                    <Tooltip title={record.status === 'active' ? '禁用用户' : '激活用户'}>
                        <Button
                            type="text"
                            icon={<UserSwitchOutlined/>}
                            onClick={() => {
                                const newStatus = record.status === 'active' ? 'inactive' : 'active';
                                updateUser(record.username, {status: newStatus})
                                    .then(response => {

                                        if (response.success) {
                                            message.success(`用户${newStatus === 'active' ? '激活' : '禁用'}成功`);
                                            fetchUsers(usersData?.currentPage || 1, usersData?.pageSize || 10);
                                        }
                                    })
                                    .catch(() => message.error('操作失败'));
                            }}
                        />
                    </Tooltip>

                    <Tooltip title="删除用户">
                        <Popconfirm
                            title="确定要删除此用户吗？"
                            onConfirm={() => handleDeleteUser(record.username)}
                            okText="是"
                            cancelText="否"
                        >
                            <Button
                                type="text"
                                danger
                                icon={<DeleteOutlined/>}
                            />
                        </Popconfirm>
                    </Tooltip>
                </Space>
            ),
        },
    ];

    const handleSearch = (value: string) => {
        setSearchText(value);
        fetchUsers(1, usersData?.pageSize || 10);
    };

    const handleReset = () => {
        setSearchText('');
        setFilterRole(null);
        setFilterStatus(null);
        setSelectedRowKeys([]);
        fetchUsers(1, usersData?.pageSize || 10);
    };

    const handleTableChange = (pagination: any, filters: any, _sorter: any) => {
        setFilterRole(filters.role && filters.role.length > 0 ? filters.role[0] : null);
        setFilterStatus(filters.status && filters.status.length > 0 ? filters.status[0] : null);

        fetchUsers(
            pagination.current,
            pagination.pageSize
        );
    };

    // 所有可用权限
    const availablePermissions = [
        {label: '查看仪表盘', value: 'view_dashboard'},
        {label: '查看报表', value: 'view_reports'},
        {label: '查看分析', value: 'view_analytics'},
        {label: '管理事件', value: 'manage_events'},
        {label: '管理用户', value: 'manage_users'},
        {label: '系统设置', value: 'system_settings'},
    ];

    return (
        <div>
            <Title level={2}>用户管理</Title>

            <Card style={{marginBottom: 16}}>
                <Row gutter={[16, 16]} align="middle">
                    <Col xs={24} sm={12} md={8} lg={6}>
                        <Search
                            placeholder="搜索用户名或邮箱"
                            value={searchText}
                            onChange={(e) => setSearchText(e.target.value)}
                            onSearch={handleSearch}
                            style={{width: '100%'}}
                            allowClear
                        />
                    </Col>

                    <Col xs={24} sm={12} md={16} lg={18}>
                        <Space wrap>
                            <Button
                                type="primary"
                                icon={<UserAddOutlined/>}
                                onClick={showAddUserModal}
                            >
                                添加用户
                            </Button>

                            <Button
                                icon={<ReloadOutlined/>}
                                onClick={handleReset}
                            >
                                重置筛选
                            </Button>

                            <Divider type="vertical"/>

                            <Tooltip title="批量激活">
                                <Button
                                    disabled={selectedRowKeys.length === 0}
                                    onClick={() => handleBulkUpdateStatus('active')}
                                    icon={<UserSwitchOutlined/>}
                                    type="text"
                                />
                            </Tooltip>

                            <Tooltip title="批量禁用">
                                <Button
                                    disabled={selectedRowKeys.length === 0}
                                    onClick={() => handleBulkUpdateStatus('inactive')}
                                    icon={<UserSwitchOutlined/>}
                                    type="text"
                                />
                            </Tooltip>

                            <Tooltip title="批量删除">
                                <Button
                                    disabled={selectedRowKeys.length === 0}
                                    onClick={handleBulkDelete}
                                    danger
                                    icon={<DeleteOutlined/>}
                                    type="text"
                                />
                            </Tooltip>
                        </Space>
                    </Col>
                </Row>
            </Card>

            {selectedRowKeys.length > 0 && (
                <Alert
                    message={`已选择 ${selectedRowKeys.length} 项`}
                    type="info"
                    showIcon
                    style={{marginBottom: 16}}
                    action={
                        <Button size="small" type="text" onClick={() => setSelectedRowKeys([])}>
                            清除
                        </Button>
                    }
                />
            )}

            {loading ? (
                <div style={{textAlign: 'center', padding: '50px'}}>
                    <Spin size="large"/>
                </div>
            ) : error ? (
                <div style={{textAlign: 'center', color: 'red', padding: '50px'}}>
                    {error}
                </div>
            ) : (
                <Card>
                    <Table
                        rowKey="username"
                        rowSelection={rowSelection}
                        columns={columns}
                        dataSource={usersData?.users || []}
                        pagination={{
                            current: usersData?.currentPage || 1,
                            pageSize: usersData?.pageSize || 10,
                            total: usersData?.totalCount || 0,
                            onChange: handlePageChange,
                            showSizeChanger: true,
                            showQuickJumper: true,
                            showTotal: (total) => `共 ${total} 条记录`,
                        }}
                        onChange={handleTableChange}
                    />
                </Card>
            )}

            {/* 用户表单模态框 */}
            <Modal
                title={modalTitle}
                open={modalVisible}
                onOk={handleModalOk}
                onCancel={() => setModalVisible(false)}
                okText="确定"
                cancelText="取消"
                width={600}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="username"
                                label="用户名"
                                rules={[
                                    {required: true, message: '请输入用户名'},
                                    {min: 3, message: '用户名至少3个字符'}
                                ]}
                            >
                                <Input
                                    prefix={<UserOutlined/>}
                                    placeholder="用户名"
                                    disabled={!!editingUser}
                                />
                            </Form.Item>
                        </Col>

                        <Col span={12}>
                            <Form.Item
                                name="displayName"
                                label="显示名称"
                            >
                                <Input placeholder="显示名称 (可选)"/>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            {!editingUser && (
                                <Form.Item
                                    name="password"
                                    label="密码"
                                    rules={[
                                        {required: !editingUser, message: '请输入密码'},
                                        {min: 6, message: '密码至少6个字符'}
                                    ]}
                                >
                                    <Input.Password prefix={<LockOutlined/>} placeholder="密码"/>
                                </Form.Item>
                            )}

                            {editingUser && (
                                <Form.Item
                                    name="password"
                                    label="密码 (留空表示不修改)"
                                    rules={[
                                        {min: 6, message: '密码至少6个字符'}
                                    ]}
                                >
                                    <Input.Password prefix={<LockOutlined/>} placeholder="新密码 (可选)"/>
                                </Form.Item>
                            )}
                        </Col>

                        <Col span={12}>
                            <Form.Item
                                name="email"
                                label="邮箱"
                                rules={[
                                    {type: 'email', message: '请输入有效的邮箱地址'}
                                ]}
                            >
                                <Input prefix={<MailOutlined/>} placeholder="邮箱 (可选)"/>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="role"
                                label="角色"
                                rules={[
                                    {required: true, message: '请选择角色'}
                                ]}
                            >
                                <Select placeholder="选择角色">
                                    <Option value="admin">管理员</Option>
                                    <Option value="user">普通用户</Option>
                                    <Option value="guest">访客</Option>
                                </Select>
                            </Form.Item>
                        </Col>

                        <Col span={12}>
                            <Form.Item
                                name="status"
                                label="状态"
                                rules={[
                                    {required: true, message: '请选择状态'}
                                ]}
                            >
                                <Select placeholder="选择状态">
                                    <Option value="active">活跃</Option>
                                    <Option value="inactive">未激活</Option>
                                    <Option value="locked">已锁定</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Divider orientation="left">权限设置</Divider>

                    <Form.Item
                        name="permissions"
                        valuePropName="checked"
                    >
                        <Checkbox.Group style={{width: '100%'}}>
                            <Row gutter={[8, 8]}>
                                {availablePermissions.map(permission => (
                                    <Col span={8} key={permission.value}>
                                        <Checkbox value={permission.value}>{permission.label}</Checkbox>
                                    </Col>
                                ))}
                            </Row>
                        </Checkbox.Group>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default Users; 